package com.atguigu.deucenter.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.deucenter.entity.UcenterMember;
import com.atguigu.deucenter.service.UcenterMemberService;
import com.atguigu.deucenter.utils.ConstantWxUtils;
import com.atguigu.deucenter.utils.HttpClientUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

//微信扫码登录
@Controller //注意这里没有配置 @RestController 因为我们只是请求地址 不需要返回数据
@RequestMapping("/api/ucenter/wx")
@CrossOrigin
public class WxApiController {

    @Autowired
    UcenterMemberService service;

    // 1 生成微信二维码
    @GetMapping("login")
    public String getVxCode() {
        // 微信开放平台授权baseUrl  %s相当与占位符
        //第一种方式
        String baseUrlOne="";
        try {
            baseUrlOne = "https://open.weixin.qq.com/connect/qrconnect?appid="
                    +ConstantWxUtils.WX_OPEN_APP_ID+"&redirect_uri="
                    + URLEncoder.encode(ConstantWxUtils.WX_OPEN_REDIRECT_URL,"UTF-8")
                    +"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //第二中方式
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" + "&redirect_uri=%s" + "&response_type=code" +
                "&scope=snsapi_login" + "&state=%s" + "#wechat_redirect";
        try {
            baseUrl = String.format(
                    baseUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    //对redirect_uri进行编码
                    URLEncoder.encode(ConstantWxUtils.WX_OPEN_REDIRECT_URL, "utf-8"),
                    "atguigu"
            );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(baseUrlOne);
        //重定向到请求微信地址
        return "redirect:" + baseUrlOne;
    }



    //2 获取扫描人信息 添加数据
    @GetMapping("callback")
    public String callback(String code, String state) throws Exception { //两个参数 code类似于手机验证码 唯一随机
        System.out.println("code:"+code);
        System.out.println("state:"+state);
        //1.通过code获取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        //拼接三个参数 id 密钥 code
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                //%s
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                code
        );
        //请求拼接好的地址 得到返回的两个值 access_code和openid
        //使用httpclient发送请求 得到返回结果
        String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
        //2.将String转换成json
        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(accessTokenInfo, HashMap.class);
        //{access_token=51_K7tdj3b7Mwcd-cqDhgw8T00wOXeu69P-uSIkZqbVEEwczVXYV_zWTpT3bf9BAoXyxO4IBhIjDQu6nuCMZwtfstU26gF_50d2hJWq9gO-C4Y, refresh_token=51_ZDvGRvnqsFwDjPErGMyz79qckgevstb3Yaqkh-A4zxKcHP3n6W476mXAsKvJW7u7S1sCGhSpZWfRe8S_AOfNaHP8743y_D--FaUMgkU_Z_s, unionid=oWgGz1C37gswvmW64kP61fzN1u40, openid=o3_SC55s8lMF80GelQ-83WgKXdh0, scope=snsapi_login, expires_in=7200}
        String accessToken = (String) map.get("access_token");
        String openid = (String) map.get("openid");
        String refreshToken= (String) map.get("refresh_token");
        System.out.println("通过code获取access_token");
        System.out.println("accessToken:"+accessToken+"\topenid:"+openid+"\trefreshToken:"+refreshToken);

//        //刷新或续期 access_token 使用
//        String url="https://api.weixin.qq.com/sns/oauth2/refresh_token?" +
//                "appid=%s" +
//                "&grant_type=refresh_token" +
//                "&refresh_token=%s";
//        url=String.format(url,
//                ConstantWxUtils.WX_OPEN_APP_ID,
//                refreshToken);
//        String accessTokenTwo = HttpClientUtils.get(url);
//        Map accessTokenTwoMap = mapper.readValue(accessTokenTwo, HashMap.class);
//        accessToken = (String) accessTokenTwoMap.get("access_token");
//        openid= (String) accessTokenTwoMap.get("openid");
//        refreshToken= (String) accessTokenTwoMap.get("refresh_token");
//        System.out.println("刷新或续期 access_token 使用");
//        System.out.println("accessToken:"+accessToken+"\topenid:"+openid+"\trefreshToken:"+refreshToken);
//
//        //检验授权凭证（access_token）是否有效
//        String urltwo="https://api.weixin.qq.com/sns/auth?access_token="+accessToken+"&openid="+openid;
//        String urltwoVo = HttpClientUtils.get(urltwo);
//        Map urltwoVoMap = mapper.readValue(urltwoVo, HashMap.class);
//        System.out.println("检验授权凭证（access_token）是否有效\t正确的Json:{errcode:0, errmsg:ok}");
//        System.out.println(urltwoVoMap);


        //根据openid判断用户是否注册过
        UcenterMember member = service.getOpenIdMember(openid);
        if(member==null){
            //如果已经注册过直接从数据库取信息
            //3.获取用户个人信息（UnionID机制）
            String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
            infoUrl=String.format(infoUrl,
                    accessToken,
                    openid);
            String userInfo = HttpClientUtils.get(infoUrl);
            Map userMap = mapper.readValue(userInfo, HashMap.class);

            String nickname= (String) userMap.get("nickname");
            Integer sex= (Integer) userMap.get("sex");
            String avatar= (String) userMap.get("headimgurl");
            String unionid= (String) userMap.get("unionid");
            //没注册过
            member=new UcenterMember();
            member.setAvatar(avatar);
            member.setSex(sex);
            member.setNickname(nickname);
            member.setOpenid(openid);
            member.setUnionid(unionid);
            service.save(member);

        }
        //cookie无法跨域 不同域名会有问题
        String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        return "redirect:http://localhost:3000?token="+ jwtToken;
    }
}
